package com.chenl.provider.DEMOS.反射相关;

import com.chenl.provider.util.ScanUtils.InterFaceScanService;
import com.chenl.provider.util.ScanUtils.InterfaceScanner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.Set;

@RestController
@Slf4j
@RequestMapping("/scanFeign")
public class ScanFeignMethodController {
    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    InterfaceScanner interfaceScanner;

    @Autowired
    InterFaceScanService interFaceScanService;

//    @Autowired
//    ConFeign conFeign;

    /**
     * 获取某个包下的所有Feign接口并执行
     * @throws Exception
     */
    @GetMapping("/test")
    public void test() throws Exception {
        Set<Class> classes = interFaceScanService.scanInterFaceByAnno("com.chenl.provider.feign", FeignClient.class);
        for (Class aClass : classes) {
            log.info("aClass---:{}", aClass.getName());
        }
        //调用方法 方式1
        for (Class clazz : classes) {
            Object bean = applicationContext.getBean(clazz);
            Method[] declaredMethods = clazz.getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                if (declaredMethod.getName().equals("objtest")) {
                    declaredMethod.invoke(bean);
                }
            }
        }
        //调用方法 方式2
        for (Class<?> aClass : classes) {
            Object bean = applicationContext.getBean(aClass);
            Method method = bean.getClass().getMethod("objtest");
            Object result = method.invoke(bean);
            System.out.println(result);
        }
    }
}
